package com.hengxinguotong.zhihuichengjian.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.VideoAdapter;
import com.hengxinguotong.zhihuichengjian.bean.Video;
import com.hengxinguotong.zhihuichengjian.bean.VideoRes;
import com.hengxinguotong.zhihuichengjian.utils.DesUtils;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.video.TempDatas;
import com.hengxinguotong.zhihuichengjian.video.UIUtils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshBase;
import com.hengxinguotong.zhihuichengjian.widget.pullrefresh.PullToRefreshListView;
import com.hikvision.netsdk.HCNetSDK;
import com.hikvision.netsdk.NET_DVR_DEVICEINFO_V30;
import com.hikvision.netsdk.NET_DVR_IPCHANINFO;
import com.hikvision.netsdk.NET_DVR_IPPARACFG_V40;
import com.hikvision.netsdk.NET_DVR_PICCFG_V30;
import com.hikvision.sdk.VMSNetSDK;
import com.hikvision.sdk.consts.HttpConstants;
import com.hikvision.sdk.net.bean.LoginData;
import com.hikvision.sdk.net.business.OnVMSNetSDKBusiness;
import com.hikvision.sdk.utils.SDKUtil;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.lang.ref.WeakReference;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.hikvision.netsdk.HCNetSDK.MAX_IP_CHANNEL;

/**
 * 单一工地下的视频列表
 * Created by liux on 2017/4/20.
 */

public class VideoListActivity extends BaseActivity implements View.OnClickListener{
    /**
     * 登录成功
     */
    public static final int LOGIN_SUCCESS = 1;
    /**
     * 登录失败
     */
    public static final int LOGIN_FAILED = 2;
    @BindView(R.id.title_tv)
    HXTextView titleTv;
    @BindView(R.id.iv_back)
    HXTextView ivBack;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.type_tv)
    HXTextView typeTv;
    @BindView(R.id.video_lv)
    PullToRefreshListView videoLv;
    private VideoAdapter videoAdapter;
    //    private List<SubResourceNodeBean> resourceNodeBeanList;
    private VideoRes videoRes;
    private int VideoType = 0;//0 NVR方式； 1 8700平台
    private Handler handler = new Handler();
    private boolean isLogin = false;
    /**
     * 发送消息的对象
     */
    private Handler mHandler = null;
    /***
     * UI处理Handler
     */
    private class ViewHandler extends Handler {
        private final WeakReference<VideoListActivity> mActivity;

        ViewHandler(VideoListActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LOGIN_SUCCESS:
                    // 登录成功
                    UIUtils.cancelProgressDialog();
                    isLogin = true;
                    break;
                case LOGIN_FAILED:
                    // 登录失败
                    UIUtils.cancelProgressDialog();
                    UIUtils.showToast(mActivity.get(), R.string.login_failed);
                    isLogin = true;
                    break;
                default:
                    break;
            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_videolist);
        ButterKnife.bind(this);
        initMeasure();
        mHandler = new ViewHandler(this);
        videoLv.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
        videoLv.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                getVideoList("加载中…");
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                getVideoList("加载中…");
            }
        });
        videoLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(isLogin){
                    Video video = videoRes.getValue().getCameraList().get(position - 1);
                    if (video.getIsOnline() == 1) {
                        Intent intent = null;
                        switch (VideoType){
                            case 0:
                                String videoInfo = videoRes.getValue().getNvrStr();
                                if(null == videoInfo){
                                    showToast("当前摄像头NVR信息为空。");
                                    return;
                                }
                                intent = new Intent(VideoListActivity.this, NVRVideoActivity.class);
                                intent.putExtra("authority", authority);
                                intent.putExtra("videoRes", videoRes);
                                intent.putExtra("position", position - 1);
                                startActivity(intent);
                                break;
                            case 1:
                                intent = new Intent(VideoListActivity.this, PlatformVideoActivity.class);
                                intent.putExtra("authority", authority);
                                intent.putExtra("videoRes", videoRes);
                                intent.putExtra("position", position - 1);
                                startActivity(intent);
                                break;
                        }
                    } else {
                        showToast("视频已离线");
                    }
                }else{
                    showToast("NVR未登录成功，当前视频无法预览");
                }

            }
        });
        handler.postDelayed(MyRunnable, 500);
    }

    private Runnable MyRunnable = new Runnable() {
        @Override
        public void run() {
            videoLv.setRefreshing();
        }
    };

    private void getVideoList(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("constructionId", SPUtil.getString(this, "constructionid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        Utils.requestData(alert, this, "/video/queryCameraList/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
        Utils.requestData(alert, this, "/video/getConstructionVideo/" + SPUtil.getString(this, "uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (videoLv.isRefreshing()) {
                    videoLv.onRefreshComplete();
                }
                if (!Utils.isEmpty(json)) {
                    process(json);
                }
            }

            @Override
            public void onFailure(String json) {
                if (videoLv.isRefreshing()) {
                    videoLv.onRefreshComplete();
                }
            }
        });
    }

    private void process(String json){
        Gson gson = new Gson();
        videoRes = gson.fromJson(json, VideoRes.class);
        if (videoRes.getValue().getCameraList().size() == 0) {
            showEmptyView(videoLv);
        } else {
            dismissEmptyView();
        }
        videoAdapter = new VideoAdapter(VideoListActivity.this, videoRes.getValue().getCameraList());
        videoLv.setAdapter(videoAdapter);
        if(videoRes.getValue().getPlatformStr() == null){
            typeTv.setVisibility(View.GONE);
            VideoType = 0;//0 NVR方式； 1 8700平台
        }else if(videoRes.getValue().getNvrStr() == null){
            typeTv.setVisibility(View.GONE);
            VideoType = 1;//0 NVR方式； 1 8700平台
        }else{
            typeTv.setVisibility(View.VISIBLE);
        }
        if(!isLogin){
            switch (VideoType) {
                case 0:
                    loginDevice();
                    break;
                case 1:
                    loginHK();
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isLogin = false;
    }

    private NET_DVR_DEVICEINFO_V30 m_oNetDvrDeviceInfoV30 = null;
    private final String TAG = "VideoListActivity";
    private String strIP;
    private int nPort = 8000;
    private String strUser;
    private String strPsd;
    private int iLogID;
    private int loginDevice() {
        String nvrStr = videoRes.getValue().getNvrStr();
        if(Utils.isEmpty(nvrStr)){
            UIUtils.showToast(this, R.string.empty_tip);
            isLogin = false;
            return -1;
        }
        try {
            nvrStr = DesUtils.decrypt(nvrStr, SPUtil.getString(this, "uuid"));
            String[] array = nvrStr.split("_");
            strIP = array[0];
            nPort = Integer.parseInt(array[1]);
            strUser = array[2];
            strPsd = array[3];
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!HCNetSDK.getInstance().NET_DVR_Init()) {
            Log.e(TAG, "HCNetSDK init is failed!");
            showToast("登录失败");
            isLogin = false;
            return -1;
        }

        // get instance
        m_oNetDvrDeviceInfoV30 = new NET_DVR_DEVICEINFO_V30();
        if (null == m_oNetDvrDeviceInfoV30) {
            Log.e(TAG, "HKNetDvrDeviceInfoV30 new is failed!");
            showToast("登录失败");
            isLogin = false;
            return -1;
        }

        // call NET_DVR_Login_v30 to login on, port 8000 as default_grey
//        HCNetSDK.getInstance().NET_DVR_SetRecvTimeOut(30000);//设置登录访问超时时间，单位：毫秒
        iLogID = HCNetSDK.getInstance().NET_DVR_Login_V30(strIP, nPort, strUser, strPsd, m_oNetDvrDeviceInfoV30);
        if (iLogID < 0) {
            String failedString = "NET_DVR_Login is failed!Err:" + HCNetSDK.getInstance().NET_DVR_GetLastError();
            showToast("登录失败");
            Log.e(TAG, failedString);
            isLogin = false;
            return -1;
        }

        Log.i(TAG, "NET_DVR_Login is Successful!");
//        showToast("用户登录成功");
        isLogin = true;
//        getVedioInfo();
        return iLogID;
    }

    //登录8700平台
    private void loginHK() {

        String platformStr = videoRes.getValue().getPlatformStr();
        if(Utils.isEmpty(platformStr)){
            isLogin = false;
            UIUtils.showToast(this, R.string.empty_tip);
        }
        try {
            platformStr = DesUtils.decrypt(platformStr, SPUtil.getString(this, "uuid"));
            Log.e("tag",platformStr);
            String[] array = platformStr.split("_");
            String vedio_ip = array[0];
            int vedio_port = Integer.parseInt(array[1]);
            String vedio_username = array[2];
            String vedio_password = array[3];
            String macAddress = getMacAddress();
            // 检查登录参数合法性
            if (Utils.isEmpty(vedio_ip) || Utils.isEmpty(macAddress)
                    || Utils.isEmpty(vedio_username) || Utils.isEmpty(vedio_password)) {
                UIUtils.showToast(this, R.string.empty_tip);
                return;
            }
            // 登录请求
            final String url = vedio_ip + ":" + vedio_port;
            String loginAddress = HttpConstants.HTTPS + url;
            UIUtils.showLoadingProgressDialog(this, R.string.loading_login_tip, false);
            VMSNetSDK.getInstance().Login(loginAddress, vedio_username, vedio_password, macAddress, new OnVMSNetSDKBusiness() {
                @Override
                public void onFailure() {
                    mHandler.sendEmptyMessage(LOGIN_FAILED);
                }

                @Override
                public void onSuccess(Object obj) {
                    if (obj instanceof LoginData) {
                        mHandler.sendEmptyMessage(LOGIN_SUCCESS);
                        //存储登录数据
                        TempDatas.getIns().setLoginData((LoginData) obj);
                        TempDatas.getIns().setLoginAddr(url);
                        //解析版本号
                        String appVersion = ((LoginData) obj).getVersion();
                        SDKUtil.analystVersionInfo(appVersion);
                    }
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 获取登录设备mac地址
    protected String getMacAddress() {
        WifiManager wm = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        String mac = wm.getConnectionInfo().getMacAddress();
        return mac == null ? "" : mac;
    }

    @OnClick({R.id.iv_back, R.id.type_tv})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.type_tv:
                showPopupWindow(view);
                break;
            case R.id.tv_high:
                VideoType = 0;
                pw.dismiss();
                typeTv.setText("NVR");
                loginDevice();
                break;
            case R.id.tv_sub:
                VideoType = 1;
                pw.dismiss();
                typeTv.setText("8700");
                loginHK();
                break;
        }
    }

    private PopupWindow pw;
    private int width;// 屏幕的宽度
    private int height;// 屏幕的高度

    //弹出一个PopupWindow的窗体
    private void showPopupWindow(View view) {
        float w = (float) (width / 6.3);
        View v = LayoutInflater.from(this).inflate(R.layout.video_popup_window, null);
        TextView tv_high = (TextView) v.findViewById(R.id.tv_high);
        tv_high.setText("NVR");
        tv_high.setOnClickListener(this);
        TextView tv_sub = (TextView) v.findViewById(R.id.tv_sub);
        tv_sub.setText("8700");
        tv_sub.setOnClickListener(this);
        TextView tv_standard = (TextView) v.findViewById(R.id.tv_standard);
        tv_standard.setVisibility(View.GONE);
        pw = new PopupWindow(v, view.getWidth() + 30, (int) w);
        pw.setFocusable(true);
        pw.setBackgroundDrawable(new BitmapDrawable());
        pw.showAsDropDown(view, 5, 10);

    }

    private void initMeasure() {
        width = getResources().getDisplayMetrics().widthPixels;
        height = getResources().getDisplayMetrics().heightPixels;
    }

    private List<Video> videoList;
    private void getVedioInfo(){
        videoList = new CopyOnWriteArrayList<>();
        NET_DVR_IPPARACFG_V40 ipcfg = new NET_DVR_IPPARACFG_V40();
        int iChannelNumber = -1;
        if(HCNetSDK.getInstance().NET_DVR_GetDVRConfig(iLogID, HCNetSDK.getInstance().NET_DVR_GET_IPPARACFG_V40, 0, ipcfg)){
            for (int chn = 0; chn < MAX_IP_CHANNEL; chn++) {
                //通道号结构体
                NET_DVR_IPCHANINFO chnStru = ipcfg.struIPChanInfo[chn];
                //byChannel表示该通道号是否被启用
                if (chnStru.byChannel > 0) {
                    //存储结构体
                    Video video = new Video();
                    video.setChannelNum(chnStru.byIPID);
                    video.setIsOnline(chnStru.byEnable);
//                    NET_DVR_PICCFG_V30 piccfg = new NET_DVR_PICCFG_V30();
//                    if((chn < m_oNetDvrDeviceInfoV30.byChanNum) && (chn >=0))
//                    {
//                        iChannelNumber = chn + m_oNetDvrDeviceInfoV30.byStartChan;
//                    }
//                    else
//                    {
//                        iChannelNumber = 32 + (chn - m_oNetDvrDeviceInfoV30.byChanNum) + m_oNetDvrDeviceInfoV30.byStartChan;
//                    }
//                    System.out.println("通道号：" + iChannelNumber);
//                    boolean picSuc = HCNetSDK.getInstance().NET_DVR_GetDVRConfig(iLogID, HCNetSDK.NET_DVR_GET_PICCFG_V30, iChannelNumber, piccfg);
//
//                    try {
//                        String[] sName = new String[2];
//                        sName = new String(piccfg.sChanName, "gb18030").split("\0", 2);
//                        ch.setName(sName[0]);
//                        System.out.println("通道名称：" + sName);
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
                    videoList.add(video);
                }
            }
            //获取通道号图像信息
            for (Video video : videoList) {
                NET_DVR_PICCFG_V30 piccfg = new NET_DVR_PICCFG_V30();
                boolean picSuc = HCNetSDK.getInstance().NET_DVR_GetDVRConfig(iLogID, HCNetSDK.NET_DVR_GET_PICCFG_V30,
                        video.getChannelNum() - 1 + m_oNetDvrDeviceInfoV30.byStartDChan, piccfg);
                if (picSuc){
                    try {
                        String sName = new String(piccfg.sChanName,"GBK");
                        video.setName(sName);
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }else{
                    int erroId = HCNetSDK.getInstance().NET_DVR_GetLastError();
                    Log.i("NVR-piccfg错误信息erroId：", erroId + "");
                }


                if(videoRes.getValue().getCameraList().contains(video.getChannelNum())){
                    videoList.remove(video);
                }else{
                }

            }
//            Iterator<Video> iterator = videoList.iterator();
//            while (iterator.hasNext()) {
//                Video video = iterator.next();
//                if(videoRes.getValue().getCameraList().contains(video.getChannelNum())){
//                    videoList.remove(video);
//                }else{
//                }
//            }
            if (videoList.size() == 0) {
                showEmptyView(videoLv);
            } else {
                dismissEmptyView();
                videoRes.getValue().setCameraList(videoList);
                videoAdapter = new VideoAdapter(VideoListActivity.this, videoRes.getValue().getCameraList());
                videoLv.setAdapter(videoAdapter);
                if(videoRes.getValue().getPlatformStr() == null){
                    typeTv.setVisibility(View.GONE);
                }
            }
        }else{
            int erroId = HCNetSDK.getInstance().NET_DVR_GetLastError();
            Log.i("NVR-ipcfg错误信息erroId：", erroId + "");
        }
    }
}
